import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import { adminRoutes } from './routes'
import { Frame } from './components'
import './App.css';

const menus = adminRoutes.filter(route => route.isNav === true)

const mapState = state => ({
  isLogin: state.user.isLogin,
  role: state.user.role
})
@connect(mapState)
class App extends Component {
  render() {
    // console.log(adminRoutes)
    return (
      this.props.isLogin
      ?
      <Frame menus={menus} >
        <Switch>
          {
            adminRoutes.map(route => {
              return (
                route.children && route.children.length > 0
                ?
                route.children.map(sub => {
                  return (
                    <Route 
                      key={sub.pathname} 
                      path={sub.pathname} 
                      exact={sub.exact} 
                      render={(routeProps) => {
                        // console.log(routeProps)
                        // console.log(sub.roles.includes(this.props.role))
                        const hasPermission = sub.roles.includes(this.props.role)
                        return hasPermission ? <sub.component {...routeProps} /> : <Redirect to="/admin/noauth" />
                      }} 
                    />
                  )
                })
                :
                <Route 
                  key={route.pathname} 
                  path={route.pathname} 
                  exact={route.exact} 
                  render={(routeProps) => {
                    // console.log(this.props)
                    // console.log(route.roles.includes(this.props.role))
                    const hasPermission = route.roles.includes(this.props.role)
                    return hasPermission ? <route.component {...routeProps} /> : <Redirect to="/admin/noauth" />
                  }} 
                />
              )
            })
          }
          <Redirect to={adminRoutes[0].pathname} from="/admin" exact />
          <Redirect to="/404" />
        </Switch>
      </Frame>
      : 
      <Redirect to="/login" />
    )
  }
}

// export default testHOC(App);
export default App